﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;

using Castle.DynamicProxy;
using Janus.Cores.Application;
using Janus.Cores.DynamicProxy.CastleDynamic.Interception;

namespace Janus.Cores.DynamicProxy.CastleDynamic
{
    /// <summary>
    /// 功能：代理生成器
    /// 作者：luochengbang
    /// 日期：2012/4/9 9:19:23 
    /// </summary>
    public abstract class jProxyGenerator
    {
        #region 私有字段
        private static readonly IInterceptorSelector interceptorSelector = new InterceptorSelector();
        private static readonly ProxyGenerator proxyGenerator = new ProxyGenerator();
        private static readonly ProxyGenerationOptions proxyGenerationOptions;
        #endregion
        /// <summary>
        /// 实例化一个代理生成器
        /// </summary>
        static jProxyGenerator()
        {
            proxyGenerationOptions = new ProxyGenerationOptions { Selector = interceptorSelector };
        }
        /// <summary>
        /// 获取生成代理
        /// </summary>
        /// <param name="targetType">目标列选</param>
        /// <param name="targetObject">目标对象</param>
        /// <returns></returns>
        public static object GetProxyObject(Type targetType, object targetObject)
        {
            IInterceptor[] interceptors = AppRuntime.Interceptors.ToArray();
            if (targetType.FullName == targetObject.GetType().FullName) return targetObject; //如果类型相同直接返回值
            if (targetType.IsInterface)
                return proxyGenerator.CreateInterfaceProxyWithTarget(targetType, targetObject, proxyGenerationOptions, interceptors);
            else
                return proxyGenerator.CreateClassProxyWithTarget(targetType, targetObject, proxyGenerationOptions, interceptors);
        }
    }
}
